package com.yupi.yupicturebackend.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.auth.StpKit;
import com.yupi.yupicturebackend.manager.message.EmailManager;
import com.yupi.yupicturebackend.mapper.UserMapper;
import com.yupi.yupicturebackend.model.dto.user.UserEditRequest;
import com.yupi.yupicturebackend.model.dto.user.UserQueryRequest;
import com.yupi.yupicturebackend.model.vo.CaptchaVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.model.dto.user.VipCode;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.UserRoleEnum;
import com.yupi.yupicturebackend.model.vo.LoginUserVO;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import org.springframework.core.io.Resource;

import static com.yupi.yupicturebackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户 服务层实现。
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @javax.annotation.Resource
    private EmailManager emailManager;

    @javax.annotation.Resource
    private StringRedisTemplate stringRedisTemplate;

//    @Override
//    public long userRegister(String userAccount, String userPassword, String checkPassword) {
//        // 1. 校验
//        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
//        }
//        if (userAccount.length() < 4) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
//        }
//        if (userPassword.length() < 8 || checkPassword.length() < 8) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
//        }
//        if (!userPassword.equals(checkPassword)) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
//        }
//        // 2. 检查是否重复
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("userAccount", userAccount);
//        long count = this.baseMapper.selectCount(queryWrapper);
//        if (count > 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
//        }
//        // 3. 加密
//        String encryptPassword = getEncryptPassword(userPassword);
//        // 4. 插入数据
//        User user = new User();
//        user.setUserAccount(userAccount);
//        user.setUserPassword(encryptPassword);
//        user.setUserName("无名");
//        user.setUserRole(UserRoleEnum.USER.getValue());
//        boolean saveResult = this.save(user);
//        if (!saveResult) {
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
//        }
//        return user.getId();
//    }
    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "yupi";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }
    @Override
    public CaptchaVO getCaptcha() {
        // 指定宽度高度以及验证码的个数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        // 验证码类型: 仅数字
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        // 获取验证码字符串 "2574", 对于数字转小写没必要, 这里是为了更通用
        String captchaCode = specCaptcha.text().toLowerCase();
        // 获取验证码图片, 转成 base64, 前端可以写在 img 标签的 src 属性中, 简化开发
        String captchaImage = specCaptcha.toBase64();
        String captchaKey = UUID.randomUUID().toString();
        // 把验证码存入 Redis 并且设置 1 分钟过期
        final String redisKey = "captcha_code_key" + captchaKey;
        stringRedisTemplate.opsForValue().set(redisKey, captchaCode, 1, TimeUnit.MINUTES);
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaKey(captchaKey);
        captchaVO.setCaptchaImage(captchaImage);
        return captchaVO;
    }
//    @Override
//    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
//        // 1. 校验
//        if (StrUtil.hasBlank(userAccount, userPassword)) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
//        }
//        if (userAccount.length() < 4) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
//        }
//        if (userPassword.length() < 8) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
//        }
//        // 2. 加密
//        String encryptPassword = getEncryptPassword(userPassword);
//        // 查询用户是否存在
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("userAccount", userAccount);
//        queryWrapper.eq("userPassword", encryptPassword);
//        User user = this.baseMapper.selectOne(queryWrapper);
//        // 用户不存在
//        if (user == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
//        }
//        // 3. 记录用户的登录态
//        request.getSession().setAttribute(USER_LOGIN_STATE, user);
//        // 记录用户登录态到Sa-token，便于空间鉴权时使用，注意保证该用户信息与springSession保持一致
//        StpKit.SPACE.login(user.getId());
//        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
//        // 4. 获得脱敏后的用户信息
//        return this.getLoginUserVO(user);
//    }

    /**
     * 用户登录
     *
     * @param userAccount  用户账号
     * @param userPassword 用户密码
     * @param captchaKey   图形验证码 key
     * @param captchaCode  图形验证码 验证码
     * @param request      存储登录信息到 session
     * @return 登录用户信息(脱敏)
     */
    @Override
// 可以使用 UserLoginRequest 作为参数
    public LoginUserVO userLogin(String userAccount, String userPassword, String captchaKey, String captchaCode, HttpServletRequest request) {
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, captchaKey, captchaCode), ErrorCode.PARAMS_ERROR);
        String redisKey = "captcha_code_key" + captchaKey;
        String redisCode = stringRedisTemplate.opsForValue().get(redisKey);
        ThrowUtils.throwIf(StrUtil.isBlank(redisCode), ErrorCode.PARAMS_ERROR, "验证码已过期");
        ThrowUtils.throwIf(!redisCode.equals(captchaCode), ErrorCode.PARAMS_ERROR, "验证码错误");
        stringRedisTemplate.delete(redisKey);
        User user;
        if(ReUtil.isMatch(RegexPool.EMAIL, userAccount)){
            // 邮箱登录
            user = this.getUserByUserEmail(userAccount);
        }else{
            // 账号登录
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userAccount", userAccount);
            user = this.getOne(queryWrapper);
        }
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        // 2. 密码加密
        String encryptPassword = getEncryptPassword(userPassword);
        if(!encryptPassword.equals(user.getUserPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }
    @Override
    public String sendEmailCode(String userEmail){
        ThrowUtils.throwIf(StrUtil.isBlank(userEmail), ErrorCode.PARAMS_ERROR);
        boolean isExist = queryUserByEmail(userEmail);

        if(isExist){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已存在");
        }
        // 发送邮箱验证码
        String code = RandomUtil.randomNumbers(6);
        emailManager.sendEmailCode(userEmail, "邮箱验证码", code);
        //生成唯一id，后面注册前端需要带过来
        String key = UUID.randomUUID().toString();
        final String redisKey = "email_code"+key+userEmail;
        stringRedisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
        return key;
    }
    /**
     * 根据用户邮箱判断用户是否存在
     *
     * @param userEmail 用户邮箱
     * @return 用户是否存在
     */
    @Override
    public boolean queryUserByEmail(String userEmail) {
        ThrowUtils.throwIf(StrUtil.isBlank(userEmail), ErrorCode.PARAMS_ERROR);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userEmail", userEmail);
        long count = this.count(queryWrapper);
        return count > 0;
    }

    @Override
    public long userRegister(String userEmail,String codeKey,String codeValue,String userPassword){
        final String redisKey = "email_code"+codeKey+userEmail;
        String code = stringRedisTemplate.opsForValue().get(redisKey);
        if (!code.equals(codeValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        //2.判断用户是否存在
        if (queryUserByEmail(userEmail)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已存在");
        }
        //3.创建用户
        User user = new User();
        String encryptPassword = this.getEncryptPassword(userPassword);
        user.setUserPassword(encryptPassword);
        user.setUserEmail(userEmail);
        user.setUserRole(UserRoleEnum.USER.getValue());
        user.setUserProfile("这个人很懒，什么都没有留下");
        user.setUserName("用户_"+RandomUtil.randomInt(9999));
        user.setUserAccount("user_"+RandomUtil.randomInt(9999));
        user.setUserAvatar("https://img.shetu66.com/2023/04/25/1682391068745168.png");
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        stringRedisTemplate.delete(redisKey);
        emailManager.sendRegisterSuccessEmail(userEmail, "智绘云图库-注册成功",userPassword);
        return user.getId();
    }

    /**
     * 根据用户邮箱查询用户
     *
     * @param userEmail 用户邮箱
     * @return 用户信息
     */
    @Override
    public User getUserByUserEmail(String userEmail) {
        ThrowUtils.throwIf(StrUtil.isBlank(userEmail), ErrorCode.PARAMS_ERROR);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userEmail", userEmail);
        return this.getOne(queryWrapper);
    }


    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    @Override
    public void editUser(UserEditRequest userEditRequest) {
        User user = new User();
        BeanUtils.copyProperties(userEditRequest, user);
        boolean result = this.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }


    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        if (StrUtil.isNotEmpty(sortField)) {
            // 使用 Hutool 将下划线转驼峰
            String actualSortField = StrUtil.toCamelCase(sortField);
            queryWrapper.orderBy(true, sortOrder.equals("ascend"), actualSortField);
        }
        return queryWrapper;
    }


    // region -------用户会员兑换逻辑---------
    /**
     * 兑换会员
     * @param user
     * @param vipCode
     * @return
     */
    @javax.annotation.Resource
    private ResourceLoader resourceLoader;
    /**
     * 文件锁，用于保证并发环境下对会员码配置文件的安全访问
     */
    private final ReentrantLock fileLock = new ReentrantLock();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeVip(User user, String vipCode) {
        // 参数校验
        if (user == null || vipCode == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户或会员码不能为空");
        }

        // 1. 验证并更新会员码状态
        boolean codeUpdated = updateVipCodeStatus(vipCode);
        if (!codeUpdated) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "会员码无效或已使用");
        }

        // 2. 更新用户会员信息
        return updateUserVipInfo(user, vipCode);
    }

    /**
     * 验证会员码并更新状态为已使用
     */
    private boolean updateVipCodeStatus(String targetCode) {
        fileLock.lock(); // 获取锁
        try {
            // 读取配置文件
            List<VipCode> vipCodeList = readVipCodeList();
            if (vipCodeList.isEmpty()) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "会员码配置为空");
            }

            // 查找未使用的目标会员码
            VipCode matchedCode = vipCodeList.stream()
                    .filter(code -> targetCode.equals(code.getCode()) && !code.isHasUsed())
                    .findFirst()
                    .orElseThrow(() -> new BusinessException(ErrorCode.SYSTEM_ERROR, "会员码无效或已使用"));

            // 标记为已使用
            matchedCode.setHasUsed(true);

            // 写入更新后的配置
            writeVipCodeList(vipCodeList);
            return true;
        } catch (Exception e) {
            log.error("更新会员码状态失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "会员码验证失败");
        } finally {
            fileLock.unlock(); // 释放锁
        }
    }
    /**
     * 更新用户会员信息（开通一年会员）
     */
    private boolean updateUserVipInfo(User user,String vipCode) {

        Date expireTime = DateUtil.offsetMonth(new Date(), 12);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUserRole(UserRoleEnum.VIP.getValue()); // 假设枚举中存在VIP角色
        updateUser.setVipExpireTime(expireTime);
        updateUser.setVipCode(vipCode); // 记录使用的会员码

        // 如果是首次开通会员，生成会员编号
        if (user.getVipNumber() == null) {
            updateUser.setVipNumber(System.currentTimeMillis());
        }

        return this.updateById(updateUser);
    }

    /**
     * 读取会员码配置列表
     */
    private List<VipCode> readVipCodeList() {
        try {
            Resource resoure = resourceLoader.getResource("classpath:biz/vipCode.json");
            String content = FileUtil.readUtf8String(resoure.getFile().getAbsolutePath());
            return JSONUtil.toList(content, VipCode.class);
        } catch (Exception e) {
            log.error("读取会员码配置失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "读取会员码配置失败");
        }
    }

    /**
     * 写入更新后的会员码配置
     */
    private void writeVipCodeList(List<VipCode> vipCodeList) {
        try {
            Resource resoure = resourceLoader.getResource("classpath:biz/vipCode.json");
            FileUtil.writeUtf8String(JSONUtil.toJsonStr(vipCodeList), resoure.getFile().getAbsolutePath());
        } catch (Exception e) {
            log.error("写入会员码配置失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新会员码状态失败");
        }
    }




    // endregion-------用户会员兑换逻辑---------
}
